<?php
/**
 * Created by PhpStorm.
 * User: winleung
 * Date: 2019-10-23
 * Time: 23:36
 */

namespace app\api\service;


use app\api\model\PharmacyModel;
use app\api\model\PharmacyOrderModel;
use dada\api\AddOrderApi;
use dada\api\BaseApi;
use dada\api\CityCodeApi;
use dada\client\DadaResponse;
use dada\config\Config;
use dada\client\DadaRequestClient;
use dada\config\UrlConfig;
use app\api\model\OrderLogistics;
use dada\model\OrderModel;
use think\Db;
use think\Request;

class PharmacyOrderService
{
    private $pharmacyOrderModel;

    private $pharmacyModel;

    private $orderLogisticsModel;

    public function __construct()
    {
        $this->pharmacyOrderModel = new PharmacyOrderModel();
        $this->pharmacyModel = new PharmacyModel();
        $this->orderLogisticsModel = new OrderLogistics();
    }

    public function fetchPharmacyOrderInfoByOrder($orderId){

        $sql = "select * from jn_pharmacy_order where order_id=?";

        $data = Db::query($sql, [$orderId]);

        if(empty($data)){
            return false;
        }else{
            return $data;
        }
    }

    /**
     * 给药店派单
     * @param $pharmacyId
     * @param $orderId
     * @return int|string
     */
    public function addPharmacyOrder($pharmacyId, $orderId)
    {
        try{

            $data = ['order_id' => $orderId, 'pharmacy_id' => $pharmacyId, 'status' => 1, 'created_at' =>date('Y-m-d H:i:s') ];

            $userId = Db::name('pharmacy_order')->insertGetId($data);

            return $userId;

        }catch (\Exception $e){
            return false;
        }


    }

    /**
     * 更新店铺订单状态
     * @param Request $request
     * @param $params
     * @return bool|null
     */
    public function updatePharmacyOrderStatus(Request $request, $params, $imageUrl = '')
    {
        $result = "";
        $updateData = [
            'status' => $params['status'],
        ];
        /**
         * 1：待接单，2：已接单，在拣货，3，已通知物流取货, 4:拒绝接单
         */
        if ($params['status'] == 3) {
            $pharmacyOrderInfo = $this->pharmacyOrderModel->getPharmacyOrderInfo($params['order_id']);

            if (!isset($pharmacyOrderInfo) || (is_array($pharmacyOrderInfo) && empty($pharmacyOrderInfo))) {
                throwBusinessException("订单分配不存在");
            }

            $sql = "select id, dl_money, recipients, recipientsMobile, recipientsAddress, latitude, longitude from jn_wx_order_info where id = " . $params['order_id'];

            $orders = Db::query($sql)[0];
            $pharmacyInfo = $this->pharmacyModel->getPharmacyInfoById(['pharmacy_id' => $pharmacyOrderInfo['pharmacy_id']]);

            if (!isset($pharmacyInfo)) {
                throwBusinessException("店铺不存在");
            }

            $cityResult = $this->getCode();

            if ($cityResult['code'] > 0) {
                throwBusinessException("获取城市列表失败");
            }
            $cityList = $cityResult['result'];
            $code = "";
            $b = [];
            // 匹配城市
            foreach ($cityList as $v) {
//                preg_match('/(.*?(' . $v['cityName'] . '))/', $pharmacyInfo['city_name'], $matches);
                if ($pharmacyInfo['city_name'] === $v['cityName'] . '市') {
                    $b = $v;
                    $code = $v['cityCode'];
                    break;
                }
            }

            $sendParams = [
                'shop_no' => $pharmacyInfo['id'],
                'origin_id' => $pharmacyOrderInfo['order_id'],
                'cargo_price' => $orders['dl_money'],
                'receiver_phone' => $orders['recipientsMobile'],
                'receiver_name' => $orders['recipients'],
                'receiver_lat' => $orders['latitude'],
                'receiver_lng' => $orders['longitude'],
                'receiver_address' => $orders['recipientsAddress'],
                'is_prepay' => 0,
                'city_code' => $code,
                'callback' => $request->domain() . config('dada_api.callback_url'),
            ];
            $dadaResult = $this->syncToDada($sendParams, UrlConfig::ORDER_ADD_URL);
            $updateData['freight'] = $dadaResult->getResult()['fee'];

            if(!empty($imageUrl)){
                $updateData['image_url'] = $imageUrl;
            }


            $result = "已通知物流取货,";
        }

        $updateResult = $this->pharmacyOrderModel->updatePharmacyOrderStatus($pharmacyInfo['id'], $pharmacyOrderInfo['order_id'], $updateData);



        if ($updateResult) {
            $result .= "更新订单状态成功";
        } else {
            $result = "更新失败";
        }

        return $result;
    }

    /**
     *
     * @return array
     */
    private function getCode()
    {
        $config = Config::newConfig();

        $cityCodeApi = new CityCodeApi("");

        $dada_client = new DadaRequestClient($config, $cityCodeApi);

        $resp = $dada_client->makeRequest();
        return (array)$resp;
    }

    public function sim($url, array $param)
    {
        $config = Config::newConfig();

        $cityCodeApi = new BaseApi($url, json_encode($param));

        $dada_client = new DadaRequestClient($config, $cityCodeApi);

        $resp = $dada_client->makeRequest();

        return (array)$resp;
    }

    /**
     * 同步到达达
     */
    private function syncToDada($params, $url): DadaResponse
    {
        $config = Config::newConfig();
        $orderModel = new OrderModel();
        $orderModel->setShopNo($params['shop_no']);    // 第三方门店编号
        $orderModel->setOriginId($params['origin_id']);            // 第三方订单号
        $orderModel->setCityCode($params['city_code']);                        // 城市code(可以参照城市code接口)
        $orderModel->setCargoPrice($params['cargo_price']);
        $orderModel->setIsPrepay($params['is_prepay']);
        $orderModel->setReceiverName($params['receiver_name'] ? $params['receiver_name'] : "默认值");
        $orderModel->setReceiverAddress(strlen($params['receiver_address']) < 1 ? "默认地址" : $params['receiver_address']);
        $orderModel->setReceiverLat($params['receiver_lat']);
        $orderModel->setReceiverLng($params['receiver_lng']);
        $orderModel->setReceiverPhone($params['receiver_phone']);
        $orderModel->setCallback($params['callback']);

        $addOrderApi = new BaseApi($url, json_encode($orderModel));

        $dada_client = new DadaRequestClient($config, $addOrderApi);
        $resp = $dada_client->makeRequest();
        if ($resp->getCode() !== 0) {
            throwBusinessException($resp->getMsg());
        }
        return $resp;
    }

    /**
     * 达达回调信息处理
     * @param $dadaCallbackParams
     */
    public function controlDadaCallback($dadaCallbackParams)
    {
        // 达达状态说明： 订单状态(待接单＝1,待取货＝2,配送中＝3,已完成＝4,已取消＝5, 已过期＝7,指派单=8,妥投异常之物品返回中=9, 妥投异常之物品返回完成=10,骑士到店=100,创建达达运单失败=1000）
        $orderStatus = 404;// 异常状态
        $where = [
            'order_id' => $dadaCallbackParams['order_id'],
            'transporter_name' => $dadaCallbackParams['dm_name'],
            'transporter_phone' => $dadaCallbackParams['dm_mobile'],
        ];
        switch ($dadaCallbackParams['order_status']) {
            case 1://待接单
                $orderStatus = 210;
                break;
            case 2://待取货
                $orderStatus = 220;
                $data = [
                    'order_id' => $dadaCallbackParams['order_id'],
                    'transporter_name' => $dadaCallbackParams['dm_name'],
                    'transporter_phone' => $dadaCallbackParams['dm_mobile'],
                    'accept_time' => date('Y-m-d H:i:s', time()),
                ];
                $insertResult = $this->orderLogisticsModel->insertLogisticsData($data);
                if (!$insertResult) {
                    trace($dadaCallbackParams, 'controlDadaCallback-status-2');
                }
                break;
            case 3://配送中
                $orderStatus = 230;
                $updateResult = $this->orderLogisticsModel->updateLogistics($where, ['fetch_time' => date('Y-m-d H:i:s', time())]);
                if (!$updateResult) {
                    trace($dadaCallbackParams, 'controlDadaCallback-status-3');
                }
                break;
            case 4://已完成
                $orderStatus = 240;
                $updateResult = $this->orderLogisticsModel->updateLogistics($where, ['finish_time' => date('Y-m-d H:i:s', time())]);
                if (!$updateResult) {
                    trace($dadaCallbackParams, 'controlDadaCallback-status-3');
                }
                break;
            case 5://已取消
                $orderStatus = 500;
                if ($dadaCallbackParams['cancel_from'] == 1) {// 达达配送员取消
                    $orderStatus = 510;
                } elseif ($dadaCallbackParams['cancel_from'] == 2) {// 商家主动取消
                    $orderStatus = 520;
                } elseif ($dadaCallbackParams['cancel_from'] == 3) {// 系统或客服取消
                    $orderStatus = 530;
                }
                $updateResult = $this->orderLogisticsModel->updateLogistics($where, ['status' => 0]);
                if (!$updateResult) {
                    trace($dadaCallbackParams, 'controlDadaCallback-status-3');
                }
                break;
            case 7://已过期
                $orderStatus = 570;
                $updateResult = $this->orderLogisticsModel->updateLogistics($where, ['status' => 0]);
                if (!$updateResult) {
                    trace($dadaCallbackParams, 'controlDadaCallback-status-3');
                }
                break;
            case 8://指派单
                $orderStatus = 580;

                break;
            case 9://妥投异常之物品返回中
                $orderStatus = 900;

                break;
            case 10://妥投异常之物品返回完成
                $orderStatus = 910;

                break;
            case 100://骑士到店
                $orderStatus = 2100;

                break;
            case 1000://创建达达运单失败
                $orderStatus = 1000;

                break;
        }
        $this->pharmacyOrderModel->updatePharmacyOrderStatus(null, $dadaCallbackParams['order_id'], $orderStatus);
    }

    public function resendOrderToDada(Request $request, $post)
    {
        $pharmacyOrderInfo = $this->pharmacyOrderModel->getPharmacyOrderInfo($post['order_id']);

        if ($pharmacyOrderInfo['status'] == 1000) {
            throwBusinessException("因达达系统异常，请调取更新订单关联表状态接口，重新下单");
        }else if ($pharmacyOrderInfo['status'] < 500 || $pharmacyOrderInfo['status'] > 570) {
            throwBusinessException("订单不可重发");
        }

        if (!isset($pharmacyOrderInfo) || (is_array($pharmacyOrderInfo) && empty($pharmacyOrderInfo))) {
            throwBusinessException("订单分配不存在");
        }

        $sql = "select id, dl_money, recipients, recipientsMobile, recipientsAddress, latitude, longitude from jn_wx_order_info where id = " . $post['order_id'];

        $orders = Db::query($sql)[0];
        $pharmacyInfo = $this->pharmacyModel->getPharmacyInfoById(['pharmacy_id' => $pharmacyOrderInfo['pharmacy_id']]);

        if (!isset($pharmacyInfo)) {
            throwBusinessException("店铺不存在");
        }

        $cityResult = $this->getCode();

        if ($cityResult['code'] > 0) {
            throwBusinessException("获取城市列表失败");
        }
        $cityList = $cityResult['result'];
        $code = "";
        $b = [];
        // 匹配城市
        foreach ($cityList as $v) {
//                preg_match('/(.*?(' . $v['cityName'] . '))/', $pharmacyInfo['city_name'], $matches);
            if ($pharmacyInfo['city_name'] === $v['cityName'] . '市') {
                $b = $v;
                $code = $v['cityCode'];
                break;
            }
        }

        $sendParams = [
            'shop_no' => $pharmacyInfo['id'],
            'origin_id' => $pharmacyOrderInfo['order_id'],
            'cargo_price' => $orders['dl_money'],
            'receiver_phone' => $orders['recipientsMobile'],
            'receiver_name' => $orders['recipients'],
            'receiver_lat' => $orders['latitude'],
            'receiver_lng' => $orders['longitude'],
            'receiver_address' => $orders['recipientsAddress'],
            'is_prepay' => 0,
            'city_code' => $code,
            'callback' => $request->domain() . config('dada_api.callback_url'),
        ];

        $dadaResult = $this->syncToDada($sendParams, UrlConfig::ORDER_ADD_URL);

        $updateData = [
            'status' => 5,
            'freight' => $dadaResult->getResult()['fee'],
        ];

        $updateData['freight'] = $dadaResult->getResult()['fee'];

        $result = "已重新物流取货,";

        $updateResult = $this->pharmacyOrderModel->updatePharmacyOrderStatus($pharmacyInfo['id'], $pharmacyOrderInfo['order_id'], $updateData);

        if ($updateResult) {
            $result .= "更新订单状态成功";
        } else {
            $result = "更新失败";
        }

        return $result;
    }

    /***
     * 查询物流信息
     * @param $orderId
     * @return array|false|\PDOStatement|string|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function fetchOrderLogistics($orderId){

        $res = Db::name('order_logistics')
            ->where('order_id', $orderId)
            ->order(['updated_at'=>'desc'])
            ->find();

        if(empty($res)){
            return [];
        }

        $status = $res['status'];

        $statusname = '';

        switch ($status){
            case 1:
                $statusname = '待接单';
                break;

            case 2:
                $statusname = '待取货';
                break;

            case 3:
                $statusname = '配送中';
                break;

            case 4:
                $statusname = '已完成';
                break;

            case 5:
                $statusname = '已取消';
                break;

            case 100:
                $statusname = '骑士到店';
                break;

            default:
                $statusname = '待处理';
        }

        $res['statusname'] = $statusname;

        if($res){
            $res['distance'] = 0;
        }

        $receiveAddress = Db::name("wx_order_info")
            ->alias('a')
            ->join('pharmacy_order b ', 'a.id=b.order_id')
            ->where('a.id', $orderId)
            ->field(['a.recipientsAddress', 'a.recipientsMobile', 'a.recipients', 'a.billNo', 'b.id as take_no'])
            ->find();

        $res['receive_info'] = $receiveAddress;

        return $res;

    }

    /**
     * 根据药店订单表的id更新状态（公共方法，不要随意改动）
     * @param $pharmacyId
     * @param $pharmacyOrderId
     * @param $updateData
     * @return bool
     */
    public function updatePharmacyOrderStatusById($pharmacyId, $pharmacyOrderId, $updateData){

        return $this->pharmacyOrderModel->updatePharmacyOrderStatusById($pharmacyId, $pharmacyOrderId, $updateData);

    }


}